package com.iloomo.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import sun.misc.BASE64Decoder;

public class UploadImage {
    public static Logger logger = Logger.getLogger(UploadImage.class);
    public static final String ALGORITHM_SHA_1 = "SHA-1";
//	 public static String endpoint = ConfigUtil.getValue(SysConstant.END_POINT);
//	 public static String accessKeyId = ConfigUtil.getValue(SysConstant.ACCESS_KEY_ID);
//	 public static String accessKeySecret = ConfigUtil.getValue(SysConstant.ACCESS_KEY_SECRET);
//	 public static String bucketName = ConfigUtil.getValue(SysConstant.BUCKET_NAME);
//


    public static String uploadImage(String url,File image, String dir, String subDir, String accessKeySecret, String accessKeyId, String endpoint, String bucketName) throws Exception {
        return uploadImage( url,image, dir, subDir, null, accessKeySecret, accessKeyId, endpoint, bucketName);
    }

    public static String uploadImage(String url,File image, String dir, String subDir, String fileOldName, String accessKeySecret, String accessKeyId, String endpoint, String bucketName) throws Exception {

        String imageSHA1 = getFileSHA1(image);
        String imageName = image.getName();
        String imageSuffix = imageName.lastIndexOf(".") > -1 ? imageName.substring(imageName.lastIndexOf(".")).toLowerCase() : "";

        if (!StringUtils.isBlank(fileOldName) && fileOldName.lastIndexOf(".") > -1) {
            imageSuffix = fileOldName.substring(fileOldName.lastIndexOf(".")).toLowerCase();
        } else if (".tmp".equals(imageSuffix)) {
            imageSuffix = ".jpg";
        }
        String filename = imageSHA1 + imageSuffix;
        String filepath = dir + "/" + subDir + "/" + filename;
        InputStream imageStream = new FileInputStream(image);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(image.length());
        // 上传图片
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, filepath, imageStream, metadata);
        String[] temp =  url.split("//");
        String fullPath = temp[0]+"//"+bucketName+"."+temp[1]+"/"+filepath;
        return fullPath;
    }


    /**
     * 上传Base64格式图片
     *
     * @param imgBase64Str
     * @param dir
     * @param subDir
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @return
     * @throws Exception
     */
    public static String uploadImageBase64(String imgBase64Str, String dir, String subDir, String endpoint, String accessKeyId, String accessKeySecret, String bucketName) throws Exception {
        //图像数据为空
        if (imgBase64Str == null) {
            throw new IllegalArgumentException("图像数据不能为空！");
        }
        BASE64Decoder decoder = new BASE64Decoder();
        String docFile = "";
        //Base64解码
        byte[] b = decoder.decodeBuffer(imgBase64Str);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {//调整异常数据
                b[i] += 256;
            }
        }
        //生成jpeg图片
        docFile = UUID.randomUUID() + ".jpg";
        String filepath = dir + "/" + subDir + "/" + docFile;

        logger.debug("filepath-->" + filepath);
        InputStream imageStream = new ByteArrayInputStream(b);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(b.length);
        // 上传图片
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, filepath, imageStream, metadata);
        return docFile;
    }

    public static String getFileSHA1(File file) throws Exception {
        return getChecksum(file, ALGORITHM_SHA_1);
    }

    public static String getChecksum(File file, String algorithm) throws Exception {
        byte[] bytes = createChecksum(file, algorithm);
        String result = "";
        for (Byte bt : bytes) {
            result += Integer.toString((bt & 0xff) + 0x100, 16).substring(1);
        }
        return result;
    }

    public static byte[] createChecksum(File file, String algorithm) throws Exception {
        InputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        MessageDigest complete = MessageDigest.getInstance(algorithm);
        int numRead;
        do {
            numRead = fis.read(buffer);
            if (numRead > 0) {
                complete.update(buffer, 0, numRead);
            }
        } while (numRead != -1);
        fis.close();
        return complete.digest();
    }

    /**
     * 上传文件
     *
     * @param
     * @param bytes
     * @param suffix
     * @param dir
     * @param subDir
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @return
     * @throws Exception
     */
    public static String uploadImageBytes(byte[] bytes, String suffix, String dir, String subDir, String endpoint, String accessKeyId, String accessKeySecret, String bucketName) throws Exception {
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        String filepath = dir + "/" + subDir + "/" + filename;
        InputStream imageStream = new ByteArrayInputStream(bytes);

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(bytes.length);

        // 上传图片
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        PutObjectResult result = ossClient.putObject(bucketName, filepath, imageStream, metadata);
        System.out.println(result.getETag());
        return filename;
    }
}
